package cn.tedu.zblogs.home.listener;


import cn.tedu.zblogs.home.utils.CacheUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义监听器:
 * 用于监听每一个前端请求的URL,IP和session id
 */
@Component //标注该类,保证SpringBoot能扫描到此监听器,即该注解让该监听器生效
public class MyRequestListener implements ServletRequestListener {
    private static final Logger log = LoggerFactory.getLogger(MyRequestListener.class);
    //redis缓存工具类
    @Autowired
    private CacheUtil cacheUtil;

    //请求初始化时触发
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        String ip = request.getRemoteAddr();
        String url = request.getRequestURL().toString();
        System.out.println(request.getServletPath());
        String sessionID = request.getSession().getId();//由服务器随机生成


        //判断是否是首页文章请求
        if(request.getServletPath() == "/home/advertisement/lselect"){
            //统计PV
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-H");
            String currentDate = dateFormat.format(new Date());//2024-09-26-15
            currentDate = "PV" + currentDate;//PV2024-09-26
            System.out.println(currentDate);
            cacheUtil.increment(currentDate);

            //统计UV
            SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd-H");
            String currentDate1= dateFormat1.format(new Date());//2024-09-26
            currentDate1 = "UV" + currentDate1;//UV2024-09-26
            cacheUtil.addSet(currentDate1,"用户Id");

        }


        System.out.println("前端请求的IP地址为: " + ip);
        System.out.println("前端请求的URL地址为: " + url);
        System.out.println("前端请求的session id地址为: " + sessionID);

    }

    //请求被销毁时触发
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
        String sessionID = request.getSession().getId();
        System.out.println("session id为: " + sessionID + "的请求已被销毁");
    }
}